<template>
  <a-space>
    <a-input
      ref="refInput"
      @focus="focus"
      v-model="inputValue"
      placeholder="选择数据来源"
    />
    <a-button @click="clear">清空</a-button>
  </a-space>
  <a-modal :width="800" v-model:visible="visible" @ok="handleOk">
    <template #title> 选择数据来源 </template>
    <div>
      <a-table
        ref="tableRef"
        :data="dataResourcesList"
        stripe
        width="100%"
        :rowKey="'id'"
        :rowSelection="{
          type: 'radio'
        }"
        :selectedKeys="selectKeys"
        @select="select"
      >
        <template #columns>
          <a-table-column title="名称">
            <template #cell="{ record }">
              {{ record.dataResourcesName }}
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import {
  getDataResourcesList,
  getDataResourcesById
} from '@/apis/dataSources/index';
import { DataResources } from '@/apis/dataSources/type';

const props = withDefaults(
  defineProps<{
    id?: number;
    dataSourcesName?: string;
  }>(),
  {}
);
const emit = defineEmits(['update:id', 'change']);
const inputValue = computed(() => {
  return props.dataSourcesName;
});
const visible = ref(false);
const refInput = ref();
const focus = () => {
  refInput.value.blur(); //使失去焦点，防止键盘输入
  visible.value = true;
};
const dataResourcesList = ref<DataResources[]>([]);
const dataResourcesParams = reactive({ pageNumber: 0, pageSize: 10 });
const getDataResources = async () => {
  const res = await getDataResourcesList(dataResourcesParams);
  dataResourcesList.value = res?.content || [];
};
const selectKeys = ref<number[]>([]);
const handleOk = () => {
  emit('update:id', selectKeys.value[0]);
  emit('change');
};
const tableRef = ref([]);
const select = (rowKeys: any, rowKey: any, recode: any) => {
  selectKeys.value = [rowKey];
};
const clear = () => {
  emit('update:id', void 0);
};
watch(
  () => visible.value,
  (val) => {
    if (val) {
      selectKeys.value = props.id ? [props.id] : [];
      getDataResources();
    }
  }
);
</script>
